package com.share.schedule.xxl.schedule;

import com.share.common.utils.DateUtil;
import com.share.common.utils.DingDingUtil;
import com.share.common.utils.HttpUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 删除大表日志
 */
@Slf4j
@Component
public class DeleteDbLogJob {

    @XxlJob("deleteDbLog")
    public void deleteDbLog() throws Exception {
        LocalDateTime start = LocalDateTime.now();
        // 分片参数
        int shardIndex = XxlJobHelper.getShardIndex();
        int shardTotal = XxlJobHelper.getShardTotal();

        XxlJobHelper.log("", shardIndex, shardTotal);
        String msg = "分片参数：当前分片序号 = {}, 总分片数 = {}";
        log.info(msg, shardIndex, shardTotal);
        XxlJobHelper.log(msg, shardIndex, shardTotal);

        String jobParam = XxlJobHelper.getJobParam();
        log.info("接收到参数JobParam={}", jobParam);
        //http://pre.snyq.ltd:8120/pre/common/deleteLog?id=-1;http://mock.snyq.ltd:8103/mock/common/deleteLog?id=-1

        if (StringUtils.isBlank(jobParam)) {
            log.info("参数配置异常需要配置参数eg： {}", "http://mock.api.snyq.ltd/deleteLog");
            return;
        }

        String lineStr = jobParam.replaceAll("\\r", "").replaceAll("\\n", "");
        XxlJobHelper.log("一行参数lineStr", lineStr);
        log.info("一行参数lineStr={}", lineStr);
        String[] arr = lineStr.split(";");
        if (arr != null && arr.length > 0) {
            for (int i = 0; i < arr.length; i++) {
                String url = null;
                try {
                    url = arr[i];
                    if (StringUtils.isBlank(url) || !url.trim().startsWith("http")) {
                        continue;
                    }
                    String res = HttpUtil.get(url);
                    log.info("请求url={},响应结果res={}", url, res);
                } catch (Exception e) {
                    log.error("执行异常url={}", url, e);
                }
            }
        }

        String title = "清理db中日志";
        String content = title + " " + DateUtil.getDateTime() + System.lineSeparator() + lineStr;
        DingDingUtil.sendMdMsg(title, content);

        LocalDateTime end = LocalDateTime.now();
        msg = "共耗时：{}毫秒";
        long costTime = Duration.between(start, end).toMillis();
        log.info(msg, costTime);
        XxlJobHelper.log(msg, costTime);
    }
}
